package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.mapper.OrdersMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.OrderDetailet;
import com.foreknow.elmboot.po.Orders;
import com.foreknow.elmboot.service.OrdersService;
import com.foreknow.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;
    @Autowired
    private CartMapper cartMapper;
    @Override
    @Transactional
    public int createOrders(Orders orders) {
        // 1. 根据用户的编号和商家的编号查询购物车列表
        // 创建Cart对象 从Orders对象中获取到userId和businessId并保存到Cart对象中;
        // List<Cart> list = 调用CartDao中的listCart(Cart c);
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart> list =  cartMapper.listCart(cart);
        //设置订单日期
        orders.setOrderDate(CommonUtil.getCurrentDate());
        //2. 创建订单并返回订单的编号（orderId）
        ordersMapper.saveOrders(orders);
        int orderId = orders.getOrderId();
        //3. 向明细表中指添加数据
        List<OrderDetailet> orderDetailetList = new ArrayList<>();
        for (Cart c:list) {
            OrderDetailet orderDetailet = new OrderDetailet();
            orderDetailet.setOrderId(orderId);
            orderDetailet.setFoodId(c.getFoodId());
            orderDetailet.setQuantity(c.getQuantity());
            //将明细对象添加到集合中
            orderDetailetList.add(orderDetailet);
        }
         orderDetailetMapper.saveBatch(orderDetailetList); //批量添加
        //4. 清除购物车
        cartMapper.removeCart(cart);
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }
}
